<?php

class g5_admin_acl extends Model{
    function __construct(){
        parent::__construct();
        $this->_tableName = 'g5_admin_acl';
    }

    function authUser() {
        $cachefile = DATA_PATH.'cache/groupacl.php';
        if(!file_exists($cachefile)){
            $acl = $this->makecache();
        }
        $acl = include $cachefile;
        $controller    =    isset($_GET[0]) ? $_GET[0] : 'index';
        $action        =    isset($_GET[1]) ? $_GET[1] : 'index';;
        $currentUri        =    $controller."+".$action;
        $user = $_SESSION['adminmanager'];
        $userAcl = $acl[$user['group_id']];
        $groupacl = array_values($userAcl);
        if(in_array($currentUri, $groupacl)){
            return true;
        }
        return false;
    }

    function makecache(){
        $admingroup = new g5_admin_group();
        $groups      = $admingroup->getAll('*');
        $aclCache = array();
        foreach ($groups as $row){
            $groupacl = $this->masterAcl($row['group_id']);
            $aclCache[$row['group_id']]    =    $groupacl;
//            $aclCache[$row['group_name']]=    $acls;
        }
        $cache = var_export($aclCache, true);
        $file  = DATA_PATH.'cache/groupacl.php';
        $contents = "<?php defined('SCRIPT_NAME') or die('No direct script access.');\r\n return {$cache} ?>";
        write_cache($file, $contents);
    }

    function masterAcl($group_id = 0) {
        $select = 'acl_value,acl_children';
        $join   = array('g5_admin_acl_group'=>'acl_id=acl_id','g5_admin_group'=>'group_id=g5_admin_acl_group.group_id');
        $where  = array('g5_admin_group.group_id'=>$group_id);
        $sql    =  $this->select($select)->join($join)->where($where)->_compile_select(false);
        $acl = parent::$db->query($sql, true)->fetch_array();
        $aclArray  = array();
        foreach ($acl as $row){
            $aclArray[]    =    $row['acl_value'];
            if($row['acl_children'] != ""){
                list($control)    =    explode("+",$row['acl_value']);
                $arrAcl        =    explode("|",$row['acl_children']);
                if(count($arrAcl)>=1){
                    foreach ($arrAcl as $cil){
                        $aclArray[]    =    $control."+".$cil;
                    }
                }
            }
        }
        return $aclArray;
    }
}